package com.bit.blog.common.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.Date;
import java.util.Map;

public class JwtUtils {
    private static final long EXPIRATION_TIME = 7 * 24 * 60 * 60 * 1000; //7天
    private static final String secretString = "kIx9zHQe56aRa3D4THlPuj+ruT1yIhTAdgxRz8VLrdA=";
    private static final Key key = Keys.hmacShaKeyFor(secretString.getBytes(StandardCharsets.UTF_8));
    /**
     * 生成令牌
     */
    public static String genJwt(Map<String, Object> map){
        return Jwts.builder()
                .setClaims(map)
                .signWith(key, SignatureAlgorithm.HS256)
                .setExpiration(new Date(System.currentTimeMillis()+EXPIRATION_TIME))
                .compact();
    }

    /**
     * 校验令牌
     */
    public static Boolean check(String token){
        if (!StringUtils.hasLength(token)){
            return false;
        }
        JwtParser build = Jwts.parserBuilder().setSigningKey(key).build();
        try {
            Claims body = build.parseClaimsJws(token).getBody();
            return true;
        }catch (Exception e){
            return false;
        }
    }
}
